﻿using System;
using System.Collections.Generic;
using Glorysoft.Auto.Xfw;
using Glorysoft.EAP.Core.Entities;
using Newtonsoft.Json;
using RestSharp;
using RestSharp.Authenticators;

namespace Glorysoft.EAP.Core
{
    public class RestApiClient
    {
        private const string BaseUrl = "https://api.twilio.com/2008-08-01";
        private readonly IRestClient client;
        private readonly string accountSid;

        public RestApiClient(string accountSid, string secretKey)
        {
            client = new RestClient(BaseUrl) {Authenticator = new HttpBasicAuthenticator(accountSid, secretKey)};
            this.accountSid = accountSid;
        }
        public RestApiClient(string url)
        {
            client = new RestClient(url);
        }

        public T Execute<T>(RestRequest request) where T : new()
        {
            var response = client.Execute<T>(request);

            if (response.ErrorException != null)
            {
                const string message = "Error retrieving response.  Check inner details for more info.";
                var ex = new Exception(message, response.ErrorException);
                throw ex;
            }
            return response.Data;
        }

        public List<EqpConfigureSECS2> GetSECS2Configure()
        {
            var list = new List<EqpConfigureSECS2>();
            try
            {
                var req = new RestRequest("/api/Syseqpcfgsecsii");
                var res = client.Execute(req);
                if (res.IsSuccessful)
                {
                    var json = JsonConvert.DeserializeObject<List<EqpConfigureSECS2>>(res.Content);
                    return json;
                }

                XfwContext.EapLogger.Error(res.ErrorException,$"RestApiClient.GetSECS2Configure() Execute Error. \n {res.ErrorMessage}");
            }
            catch (Exception ex)
            {
                XfwContext.EapLogger.Error(ex,$"RestApiClient.GetSECS2Configure() Execute Error.");
            }
            return list;
        }
    }
}
